package com.kuangstudy.kaptcha.web;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/12/26 18:25
 */
@Controller
public class KaptchaController {

    @Autowired
    private Producer producer;
    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        String text = producer.createText();
        BufferedImage bufferedImage = producer.createImage(text);
        // 将验证码翻入到session
        session.setAttribute("code", text);
        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            applicationContext.publishEvent(new ContextRefreshedEvent(applicationContext));
            OutputStream outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
